<template>
  <el-button
    v-if="!isRecording"
    :title="$t('pageKvm.brandTitle.recorder')"
    :icon="VideoPlay"
    @click="record"
  />
  <el-button
    v-else
    class="text-red-700 border-[--el-button-hover-border-color] bg-[--el-button-hover-bg-color]"
    :title="$t('pageKvm.recording')"
    :icon="Remove"
    @click="stopRecord"
  />
  <div class="fixed h-5 w-10 top-0 left-0" v-if="isRecording" id="record-block">
    <p class="text-white">{{ $t('pageKvm.recording') }}: {{ recordingTime }}</p>
  </div>
</template>

<script setup lang="ts">
import RecordRTC from 'recordrtc';
import { Remove, VideoPlay } from '@element-plus/icons-vue';

const recorder = ref();
const isRecording = ref(false);
const recordingSeconds = ref(0);
const timer = ref();

const props = defineProps<{ element: HTMLDivElement }>();

const recordingTime = computed(() => secondsToHms(recordingSeconds.value));

const secondsToHms = (seconds: number) => {
  let hours: string | number = Math.floor(seconds / 3600);
  let minutes: string | number = Math.floor((seconds % 3600) / 60);
  let remainingSeconds: string | number = seconds % 60;
  hours = hours < 10 ? '0' + hours : hours;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  remainingSeconds =
    remainingSeconds < 10 ? '0' + remainingSeconds : remainingSeconds;
  return `${hours}:${minutes}:${remainingSeconds}`;
};
const record = () => {
  timer.value = setInterval(() => {
    recordingSeconds.value++;
  }, 1000);
  let stream = (props.element as any).captureStream();
  recorder.value = new RecordRTC(stream, {
    type: 'video',
  });
  recorder.value.startRecording();
  isRecording.value = true;
};
const stopRecord = () => {
  clearInterval(timer.value);
  recorder.value.stopRecording(() => {
    let blob = recorder.value.getBlob();
    let link = document.createElement('a');
    let URL = window.URL.createObjectURL(blob);
    let filename =
      'record-' +
      new Date()
        .toLocaleString()
        .replace(/\//g, '')
        .replace(/ /g, '')
        .replace(/:/g, '');
    [link.href, link.download] = [URL, filename];
    link.click();
    isRecording.value = false;
  });
};
</script>
